<?php
namespace app\restaurant\model;

use app\BaseModel;
use think\facade\Db;

class CouponRecord extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_restaurant_coupon_record';


    protected $append = [

        'end_time_text',

        'create_time_text',

        'store',

        'cate',

        'goods',
    ];


    /**
     * @author chenniang
     * @DataTime: 2020-11-09 14:49
     * @功能说明:
     */
    public function getCreateTimeTextAttr($value,$data){

        if(!empty($data['create_time'])){

            return date('Y-m-d H:i:s',$data['create_time']);
        }
    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-23 15:27
     * @功能说明:到期时间
     */
    public function getEndTimeTextAttr($value,$data){

        if(isset($data['start_time'])&&isset($data['end_time'])){

            if($data['start_time']==0){

                $end_time = $data['end_time']-time();

                return lbGetDates($end_time);
            }else{

                return date('Y-m-d H:i:s',$data['start_time']).'~'.date('Y-m-d H:i:s',$data['end_time']);
            }

        }

    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-21 13:46
     * @功能说明:判断是否过期
     */
    public function getStatusAttr($value,$data){

        if(isset($data['time_type'])&&isset($data['end_time'])&&$data['time_type']==0&&$data['end_time']<time()){

            $value = 2;
        }

        return $value;
    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-10 17:10
     * @功能说明:门店
     */
    public function getStoreAttr($value,$data){

        if(!empty($data['id'])){

            $arr = $this->getDataSelect($data['id'],3);

            return $arr;

        }

    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-10 17:10
     * @功能说明:门店
     */
    public function getCateAttr($value,$data){

        if(!empty($data['id'])){

            $arr = $this->getDataSelect($data['id'],1);

            return $arr;

        }

    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-10 17:10
     * @功能说明:门店
     */
    public function getGoodsAttr($value,$data)
    {

        if (!empty($data['id'])) {

            $arr = $this->getDataSelect($data['id'], 2);

            return $arr;

        }

    }

    /**
     * @param $id
     * @param $type
     * @功能说明:
     * @author chenniang
     * @DataTime: 2020-10-10 17:24
     */

    public function getDataSelect($id,$type){


        if(empty($this->coupon_limit_model)){

            $this->coupon_limit_model = new CouponLimit();

        }

        $dis = [

            'a.coupon_id' => $id,

            'a.type'      => $type,

            'a.is_record' => 1
        ];

        $arr = $this->coupon_limit_model->getDataSelect($type,$dis);

        return $arr;

    }


        /**
     * @author chenniang
     * @DataTime: 2020-10-20 15:30
     * @功能说明:已经领取的优惠券
     */
    public function couponGet($user_id,$uniacid,$coupon){

        $insert = [

            'user_id'     => $user_id,

            'uniacid'     => $uniacid,

            'coupon_id'   => $coupon['id'],

            'title'       => $coupon['title'],

            'full'        => $coupon['full'],

            'discount'    => $coupon['discount'],

            'text'        => $coupon['text'],

            'start_time'  => $coupon['start_time'],

            'end_time'    => $coupon['time_type']==1?time()+$coupon['day']*86400:$coupon['end_time'],

            'all_store'   => $coupon['all_store'],

            'foods_house' => $coupon['foods_house'],

            'foods_out'   => $coupon['foods_out'],

            'limit_type'  => $coupon['limit_type'],

            'active_text' => $coupon['active_text'],

            'create_time' => time(),

            'update_time' => time(),

        ];
        //添加优惠券
        $this->insert($insert);
        //获取id
        $record_id = $this->getLastInsID();

        $coupon_limit_model = new CouponLimit();
        //该优惠券的限用内容
        $limit_data = $coupon_limit_model->where(['coupon_id'=>$coupon['id'],'is_record'=>0])->field('uniacid,obj_id,type')->select()->toArray();
        //添加领取记录的限用记录
        $coupon_limit_model->indexCouponAdd($limit_data,$record_id);

        $coupon_model = new Coupon();

        $res = $coupon_model->where(['id'=>$coupon['id'],'update_time'=>$coupon['update_time']])->update(['stock'=>$coupon['stock']-1,'update_time'=>$coupon['update_time']+1]);

        if($res!=1){

            return ['code'=>500,'msg'=>'领取人数过多，请稍后重试'];
        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-21 14:14
     * @功能说明:判断是否有
     */

    public function isHaveCanUse(){





    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-22 17:52
     * @功能说明:可以使用的卡券列表
     */
    public function canUseCoupon($order,$user_id,$uniacid,$use_type,$store_id){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['user_id','=',$user_id];
        //结束是假
        $dis[] = ['end_time','>',time()];
        //开始时间
        $dis[] = ['start_time','<',time()];
        //未使用
        $dis[] = ['status','=',0];
        //外卖
        if(in_array($use_type,[0,2])){

            $dis[] = ['foods_out','=',1];
        }
        //堂食
        if(in_array($use_type,[1])){

            $dis[] = ['foods_house','=',1];
        }
        //先查出所有优惠券
        $coupon = $this->where($dis)->order('id desc')->select()->toArray();

        $coupon_limit = new CouponLimit();

        if(!empty($coupon)){

            foreach ($coupon as $key=> &$value){

                $goods_price = 0;

                foreach ($order['list'] as $v){

                    $now_price = $v['true_price']*$v['num'];

                    $dis = [

                        'is_record' => 1,

                        'type'      => $value['limit_type'],

                        'uniacid'   => $value['uniacid'],

                        'coupon_id' => $value['id']
                    ];

                    $obj_id = $coupon_limit->where($dis)->column('obj_id');
                    //检测是否在该分类中
                    if($value['limit_type']==1&&!in_array($v['cate_id'],$obj_id)){

                        $now_price = 0;

                    }
                    //检测是否在该商品中
                    if($value['limit_type']==2){

                        $goods_model = new Goods();

                        $obj_id  = $goods_model->where('top_id','in',$obj_id)->column('id');

                        if(!in_array($v['goods_id'],$obj_id)){

                            $now_price = 0;
                        }

                    }
                    //检测限用门店
                    if($value['all_store']==0){

                        $dis['type'] = 3;

                        $obj_id = $coupon_limit->where($dis)->column('obj_id');

                        if(!in_array($store_id,$obj_id)){

                            $now_price = 0;

                        }

                    }

                    $goods_price+=$now_price;
                }
                //剔除不合格的
                if($goods_price==0||$goods_price<$value['full']){

                    unset($coupon[$key]);
                }

            }

        }

        return array_values($coupon);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-23 15:55
     * @功能说明:详情
     */

    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-03 18:10
     * @功能说明:判断优惠券实际可支付的钱
     */
    public function getCouponTruePrice($list,$coupon_id){

        if(empty($coupon_id)){

            return 0;
        }

        $coupon  = $this->dataInfo(['id'=>$coupon_id]);

        $coupon_limit = new CouponLimit();

        $goods_price = 0;

        foreach ($list as $v){

            $now_price = $v['true_price']*$v['num'];

            $dis = [

                'is_record' => 1,

                'type'      => $coupon['limit_type'],

                'uniacid'   => $coupon['uniacid'],

                'coupon_id' => $coupon['id']
            ];

            $obj_id = $coupon_limit->where($dis)->column('obj_id');
            //检测是否在该分类中
            if($coupon['limit_type']==1&&!in_array($v['cate_id'],$obj_id)){

                $now_price = 0;

            }
            //检测是否在该商品中
            if($coupon['limit_type']==2){

                $goods_model = new Goods();

                $obj_id  = $goods_model->where('top_id','in',$obj_id)->column('id');

                if(!in_array($v['goods_id'],$obj_id)){

                    $now_price = 0;
                }
            }

            $goods_price+=$now_price;

        }

        $price = $coupon['discount']>$goods_price?$goods_price:$coupon['discount'];

        return round($price,2);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-12 15:36
     * @功能说明:处理用户过期的券
     */
    public function endRecord($user_id){

        $dis[] = ['user_id','=',$user_id];

        $dis[] = ['end_time','<',time()];

        $dis[] = ['status','=',0];

        $res = $this->where($dis)->update(['status'=>2]);

//        dump($res);exit;

        return $res;


    }

}